package com.emm.yixun.customer.service.impl.app.manage;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.activiti.bpmn.model.BpmnModel;
import org.activiti.bpmn.model.FlowElement;
import org.activiti.bpmn.model.UserTask;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.history.ProcessInstanceHistoryLog;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.emm.yixun.basic.mapper.PriceSchemeMapper;
import com.emm.yixun.basic.service.AppPushService;
import com.emm.yixun.basic.service.CustomerService;
import com.emm.yixun.basic.service.DictionaryService;
import com.emm.yixun.basic.service.FamilyMemberService;
import com.emm.yixun.basic.service.ImageService;
import com.emm.yixun.basic.service.MessageReceiverService;
import com.emm.yixun.basic.service.NoticeService;
import com.emm.yixun.basic.service.PayDepositService;
import com.emm.yixun.basic.service.PriceSchemeDetailService;
import com.emm.yixun.basic.service.ProjectRoomService;
import com.emm.yixun.basic.service.ProjectService;
import com.emm.yixun.basic.service.ProjectSettingService;
import com.emm.yixun.basic.service.UserService;
import com.emm.yixun.common.app.EditPayDepositReqDto;
import com.emm.yixun.common.app.EditPayDepositResDto;
import com.emm.yixun.common.app.base.CommonResDTO;
import com.emm.yixun.common.app.servletentity.CustomerFamilyListReq;
import com.emm.yixun.common.app.servletentity.ImageListReq;
import com.emm.yixun.common.enums.ResultEnum;
import com.emm.yixun.common.model.Customer;
import com.emm.yixun.common.model.Dictionary;
import com.emm.yixun.common.model.FamilyMember;
import com.emm.yixun.common.model.PayDeposit;
import com.emm.yixun.common.model.PriceScheme;
import com.emm.yixun.common.model.PriceSchemeDetail;
import com.emm.yixun.common.model.ProjectRoom;
import com.emm.yixun.common.model.ProjectSetting;
import com.emm.yixun.common.model.User;
import com.emm.yixun.common.model.dto.CustomerDto;
import com.emm.yixun.common.model.dto.DictionaryDto;
import com.emm.yixun.common.model.dto.FamilyMemberDto;
import com.emm.yixun.common.model.dto.ImageDto;
import com.emm.yixun.common.model.dto.MessageReceiverDto;
import com.emm.yixun.common.model.dto.NoticeDto;
import com.emm.yixun.common.model.dto.PayDepositDto;
import com.emm.yixun.common.model.dto.ProjectSettingDto;
import com.emm.yixun.common.model.dto.UserDto;
import com.emm.yixun.common.model.enums.AuditStatusEnum;
import com.emm.yixun.common.model.enums.DelFlagEnum;
import com.emm.yixun.common.model.enums.ImgTypeEnum;
import com.emm.yixun.common.model.enums.IsPaydepositEnum;
import com.emm.yixun.common.model.enums.IsSendEnum;
import com.emm.yixun.common.model.enums.MemberTypeEnum;
import com.emm.yixun.common.model.enums.RoomStatusEnum;
import com.emm.yixun.common.model.enums.SexEnum;
import com.emm.yixun.common.utils.FileUploadPorxyUtil;
import com.emm.yixun.common.utils.MsgUtil;
import com.emm.yixun.common.utils.SequencesGenerator;
import com.emm.yixun.customer.service.impl.app.ActivitiProcessServiceImpl;

@Service("editPayDepositManage")
public class EditPayDepositManage {

	@Autowired
	private CustomerService customerService;
	@Autowired
	private PayDepositService payDepositService;
	@Autowired
	private FamilyMemberService familyMemberService;
	@Autowired
	private ProjectRoomService projectRoomService;
	@Autowired
	private PriceSchemeDetailService priceSchemeDetailService;
	@Autowired
	private DictionaryService dictionaryService;
	@Autowired
	private ProjectService projectService;
	@Autowired
	private UserService userService;
	@Autowired
	private CusAppNoticeManage cusAppNoticeManage;
	@Autowired
	private MessageReceiverService messageReceiverService;
	@Autowired
	private NoticeService noticeService;
	@Autowired
	private AppPushService appPushService;
	@Autowired
	private ProjectSettingService projectSettingService;
	@Autowired
	private HistoryService historyService;
	@Autowired
	private RepositoryService repositoryService;
	@Autowired
	private PriceSchemeMapper priceSchemeMapper;
	@Autowired
	private ActivitiProcessServiceImpl activitiProcessService;
	@Autowired
	private ImageService imageService;
	@Value("${file.serviceUrl}")
	private String fileUploadUrl;
	
	/**
	 * 修改客户认筹
	 * @param reqDto
	 * @return
	 */
	public EditPayDepositResDto editPayDeposit(EditPayDepositReqDto reqDto) {
		EditPayDepositResDto resDto = new EditPayDepositResDto();
		try{
			PayDeposit payDeposit = payDepositService.selectById(Long.parseLong(reqDto.getPayDepositId()));
			if(payDeposit == null){
				resDto.setErrorCode("00001");
				resDto.setErrorMsg("认筹记录不存在!");
				resDto.setResult(ResultEnum.FAILURE.getNo());
				return resDto;
			}
			
			String roomId = reqDto.getRoomId();
			if(roomId != null && !"".equals(roomId) && !"null".equals(roomId)){
				ProjectRoom room = projectRoomService.selectById(Long.parseLong(roomId));
				if(room != null){
					String roomStatus = room.getRoomStatus();
					//可售或认筹状态可认筹
					if(!RoomStatusEnum.VENDIBILITY.getNo().equals(roomStatus) && !RoomStatusEnum.RESERVE.getNo().equals(roomStatus)){
						resDto.setErrorCode("00000");
						resDto.setErrorMsg("此房源状态为:"+RoomStatusEnum.getByNo(roomStatus).getDes()+",房源不可认筹!");
						resDto.setResult(ResultEnum.FAILURE.getNo());
						return resDto;
					}
				} else {
					resDto.setErrorCode("00000");
					resDto.setErrorMsg("房源不存在");
					resDto.setResult(ResultEnum.FAILURE.getNo());
					return resDto;
				}
			}
			//校验认筹号是否重复
			if(reqDto.getPayDepositCode() != null && !"".equals(reqDto.getPayDepositCode())){
				PayDepositDto pd_dto = new PayDepositDto();
				pd_dto.setMerchantId(reqDto.getMerchantId());
				pd_dto.setProjectCode(reqDto.getProjectCode());
				pd_dto.setDepositCode(reqDto.getPayDepositCode());
				List<PayDeposit> payDepositList =  payDepositService.selectListByDto(pd_dto);
				if(payDepositList.size() > 0){
					resDto.setErrorCode("00000");
					resDto.setErrorMsg("已经存在该认筹号!");
					resDto.setResult(ResultEnum.FAILURE.getNo());
					return resDto;
				}
			}
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			//1、修改客户认筹
			PayDepositDto payDepositDto = new PayDepositDto();
			payDepositDto.setId(payDeposit.getId());
			payDepositDto.setProjectId(reqDto.getProjectId());
			payDepositDto.setProjectCode(reqDto.getProjectCode());
			payDepositDto.setDepositCode(reqDto.getPayDepositCode());
			payDepositDto.setIsPaydeposit(reqDto.getIsPayDeposit());
			if(StringUtils.isNotEmpty(reqDto.getRoomId()) && !"null".equals(reqDto.getRoomId())){
				payDepositDto.setRoomId(Long.parseLong(reqDto.getRoomId()));
				PriceScheme priceScheme = priceSchemeMapper.selectEntityByRoomId(Long.parseLong(reqDto.getRoomId()));
				if(priceScheme != null){
					payDepositDto.setFloorType(priceScheme.getFloorType());
				}
			}
			if(StringUtils.isNotEmpty(reqDto.getCalculateArea())){
				payDepositDto.setCalculateArea(new BigDecimal(reqDto.getCalculateArea()));
			}
			if(StringUtils.isNotEmpty(reqDto.getDiscountPrice())){
				payDepositDto.setDiscountPrice(new BigDecimal(reqDto.getDiscountPrice()));
			}
			if(StringUtils.isNotEmpty(reqDto.getDiscountTotalPrice())){
				/*payDepositDto.setDiscountTotalPrice(new BigDecimal(Double.valueOf(reqDto.getDiscountTotalPrice())*10000));*/
				payDepositDto.setDiscountTotalPrice(new BigDecimal(Double.valueOf(reqDto.getDiscountTotalPrice())));
			}
			if(StringUtils.isNotEmpty(reqDto.getPayDepositMoney())){
				payDepositDto.setPayDepositAmount(new BigDecimal(reqDto.getPayDepositMoney()));
			}
			payDepositDto.setAgentId(Long.parseLong(reqDto.getAgentId()));
			//修改后的经纪人与修改前不一致,记录上一个经纪人信息
			if(Long.parseLong(reqDto.getAgentId()) != payDeposit.getAgentId()){
				payDepositDto.setLastAgentId(payDeposit.getAgentId());
			}
			payDepositDto.setDidTime(sdf.parse(reqDto.getPayDepositDate()));
			payDepositDto.setAuditStatus(reqDto.getAuditStatus());
			payDepositDto.setUpdateUserId(Long.parseLong(reqDto.getUserId()));
			payDepositDto.setRemark(reqDto.getRemark());
			//折扣比例，最大浮动范围
			if(reqDto.getRoomId() != null && !"".equals(reqDto.getRoomId())){
				PriceSchemeDetail priceSchemeDetail = priceSchemeDetailService.selectEntityByRoomId(Long.valueOf(reqDto.getRoomId()));
				if(priceSchemeDetail != null){
					if(priceSchemeDetail.getDiscountRate() != null){
						payDepositDto.setDiscountRate(priceSchemeDetail.getDiscountRate());
					}else{
						payDepositDto.setDiscountRate(null);
					}
					if(priceSchemeDetail.getFloatingRange() != null){
						payDepositDto.setFloatingRange(priceSchemeDetail.getFloatingRange());
					}else{
						payDepositDto.setFloatingRange(null);
					}
				}
			}
			
			payDepositService.update(payDepositDto);
			
			//更新客户信息
			CustomerDto customerDto = new CustomerDto();
			customerDto.setId(payDeposit.getCustomerId());
			customerDto.setCustomerName(reqDto.getMemberName());
			customerDto.setPeDocumentType(reqDto.getDocumentType());
			customerDto.setPeDocumentNumber(reqDto.getDocumentNumber());
			customerDto.setCustomerPhone(reqDto.getMobile());
			customerDto.setPeContactAddress(reqDto.getMailPost());
			customerDto.setPePostcode(reqDto.getPostcode());
			customerService.update(customerDto);
			
			//修改客户家庭成员
			CommonResDTO commonResDTO = editCusFamily(payDeposit, reqDto);
			if(StringUtils.isNotEmpty(commonResDTO.getErrorCode())){
				resDto.setErrorCode(commonResDTO.getErrorCode());
				resDto.setErrorMsg(commonResDTO.getErrorMsg());
				resDto.setResult(ResultEnum.FAILURE.getNo());
				return resDto;
			}
			
			//新增合同附件【图片】
			if (reqDto.getImageList() != null) {
				List<ImageListReq> imageList = reqDto.getImageList();
				CommonResDTO commonResDto_image = editPayDepositImage(payDeposit, imageList);
				if (StringUtils.isNotEmpty(commonResDto_image.getErrorCode())) {
					// 抛出异常
					throw new Exception("image");
				}
			}
			
			resDto.setResult(ResultEnum.SUCCESS.getNo());
		}catch(Exception e){
			e.printStackTrace();
			resDto.setErrorCode("00000");
			resDto.setErrorMsg("修改认筹失败!");
			resDto.setResult(ResultEnum.FAILURE.getNo());
			return resDto;
		}
		return resDto;
	}
	
	/**
	 * 修改客户认筹家庭成员
	 * @param reqDto
	 * @return
	 */
	public CommonResDTO editCusFamily(PayDeposit payDeposit, EditPayDepositReqDto reqDto) {
		CommonResDTO resDto = new CommonResDTO();
		try{
			//1、修改认筹家庭成员
			//1.1、先删除家庭成员
			//1.2、再添加新的家庭成员
			//删除客户原有家庭成员,修改del_flag = 1
			FamilyMemberDto fmDto_update = new FamilyMemberDto();
			fmDto_update.setBuyId(payDeposit.getId());
			List<FamilyMember> familyMemberList = familyMemberService.selectListByDto(fmDto_update);
			if(familyMemberList != null && familyMemberList.size() > 0){
				for(FamilyMember familyMember : familyMemberList){
					FamilyMemberDto fmDto_del = new FamilyMemberDto();
					fmDto_del.setId(familyMember.getId());
					familyMemberService.destroy(fmDto_del);
				}
			}
			
			FamilyMemberDto fmDto = new FamilyMemberDto();
			List<CustomerFamilyListReq> cusFmReqList = reqDto.getCustomerFamilyList();
			int index = 0;
			if(cusFmReqList != null){
				for (CustomerFamilyListReq family: cusFmReqList) {
					fmDto = new FamilyMemberDto();
					fmDto.setCustomerId(payDeposit.getCustomerId());
					fmDto.setProjectId(payDeposit.getProjectId());
					fmDto.setProjectCode(payDeposit.getProjectCode());
					fmDto.setBuyId(payDeposit.getId());
					fmDto.setMemberName(family.getMemberName());
					fmDto.setSex(SexEnum.UNKNOW.getNo());
					fmDto.setDocumentType(family.getDocumentType());
					fmDto.setDocumentNumber(family.getDocumentNumber());
					fmDto.setMobile(family.getMobile());
					fmDto.setMemberType(MemberTypeEnum.DEPOSIT.getNo());
					fmDto.setMailPost(family.getMailPost());
					fmDto.setPostcode(family.getPostcode());
					if(index == 0){
						fmDto.setIsDefault("1");
					}else{
						fmDto.setIsDefault("0");
					}
					fmDto.setMerchantId(payDeposit.getMerchantId());
					fmDto.setUserCode(payDeposit.getUserCode());
					fmDto.setAccessCode(payDeposit.getAccessCode());
					fmDto.setCreateUserId(payDeposit.getCreateUserId());
					fmDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
					fmDto.setRemark("认筹家庭成员");
					familyMemberService.create(fmDto);
					index++;
				}
			}
			resDto.setResult(ResultEnum.SUCCESS.getNo());
		}catch(Exception e){
			e.printStackTrace();
			resDto.setErrorCode("00000");
			resDto.setErrorMsg("修改认筹失败!");
			resDto.setResult(ResultEnum.FAILURE.getNo());
			return resDto;
		}
		return resDto;
	}

	/**
	 * 修改合同附件【图片】
	 * 
	 * @param payDepositDto 认购记录
	 * @param imageList 图片列表
	 * @return 
	 */
	public CommonResDTO editPayDepositImage(PayDeposit payDeposit, List<ImageListReq> imageList){
		CommonResDTO resDto = new CommonResDTO();
		try {
			for (ImageListReq image: imageList) {
				// 上传头像后缀名：例如【.jpg】（如入参为0 则代表图片保持不变；入参为 1 则代表改图片做删除）
				if ("1".equals(image.getHeadType())) {
					ImageDto dto_img = new ImageDto();
					dto_img.setSmallUrl(image.getSignedUrl());
					imageService.destroy(dto_img);
				} else if (!"1".equals(image.getHeadType()) && !"0".equals(image.getHeadType())) {
					String imgName = SequencesGenerator.getUUID("IMG")+ image.getHeadType();
					String result = FileUploadPorxyUtil.appPost(fileUploadUrl, image.getSignedUrl(), imgName);
					JSONObject resultJson = JSON.parseObject(result);
					String postResult = resultJson.getString("result");
					if (!"1".equals(postResult)) {
						resDto.setResult(ResultEnum.FAILURE.getNo());
						resDto.setErrorCode("00000");
						resDto.setErrorMsg("认筹合同附件图片上传失败");
						return resDto;
					}
					String postUrl = resultJson.getString("url");
					ImageDto imageDto = new ImageDto();
					imageDto.setObjectId(payDeposit.getId());
					imageDto.setSmallUrl(postUrl);
					imageDto.setImgType(ImgTypeEnum.PAYDEPOSIT.getNo());
					imageDto.setMerchantId(payDeposit.getMerchantId());
					imageDto.setUserCode(payDeposit.getUserCode());
					imageDto.setAccessCode(payDeposit.getAccessCode());
					imageDto.setRemark("认筹合同附件");
					imageDto.setCreateUserId(payDeposit.getCreateUserId());
					imageDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
					imageService.create(imageDto);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			resDto.setErrorCode("00000");
			resDto.setErrorMsg("新增合同附件失败!");
			resDto.setResult("0");
			return resDto;
		}
		return resDto;
	}
	
	/**
	 * 新增客户认筹推送push消息
	 * 
	 * @param payDepositDto 认筹记录
	 * @return 
	 */
	public CommonResDTO editPayDepositNotice(PayDeposit payDepositDto){
		CommonResDTO resDto = new CommonResDTO();
		try {
			//待审核数据,发送消息
			if(AuditStatusEnum.AUDIT.getNo().equals(payDepositDto.getAuditStatus())){
				//客户
				String cusName = "";
				Customer customer = customerService.selectById(payDepositDto.getCustomerId());
				if(customer != null){
					cusName = customer.getCustomerName();
				}
				
				/**
				 * 消息接收人
				 * 1、根据审批节点人员确定
				 */
				//获取当前项目下审批节点人map
				ProjectSettingDto pDto = new ProjectSettingDto();
				pDto.setProjectCode(payDepositDto.getProjectCode());
				ProjectSetting pObj = projectSettingService.selectByDto(pDto);
				Map<String, Object> variables = new HashMap<String, Object>();
				variables.put("projectApprovalUser", pObj.getProjectLeader());
				variables.put("marketingApprovalUser", pObj.getSaleLeader());
				variables.put("caseApprovalUser", pObj.getFieldLeader());
				variables.put("financeApprovalUser", pObj.getFinanceLeader());
				variables.put("saleManagerApprovalUser", pObj.getMaLeader());
				
				//获取审批人userId
				List<User> userList = new ArrayList<User>();
				ProcessInstanceHistoryLog processInstanceHistoryLog = historyService.createProcessInstanceHistoryLogQuery(payDepositDto.getProcInstId()).singleResult();
				BpmnModel model = repositoryService.getBpmnModel(processInstanceHistoryLog.getProcessDefinitionId());  
				if(model != null) {  
					Collection<FlowElement> flowElements = model.getMainProcess().getFlowElements();  
					for(FlowElement e : flowElements) { 
						if(e instanceof UserTask){
							List<String> userIds = activitiProcessService.getNodeUserId(payDepositDto.getMerchantId(),null,processInstanceHistoryLog.getProcessDefinitionId(),e.getId());
							for(String userId : userIds){
								User user = new User();
								user.setId(Long.valueOf(userId));
								userList.add(user);
							}
						}
					}  
				}
				
				//项目
				/*String proName = "";
				Project project = null;
				if(payDepositDto.getProjectId() != null){
					project = projectService.selectById(payDepositDto.getProjectId());
					if(project != null){
						proName = project.getProjectName();
					}
				}*/
				
				//获取经纪人
//				User userAgent = userService.selectById(payDepositDto.getAgentId());''
				//获取归属人
				UserDto userDto = new UserDto();
				userDto.setUserCode(customer.getUserCode());
				User userAgent_gsr = userService.selectByDto(userDto);
				
				String action = "认筹提交审核提醒";
				
				//判断是否无房认筹: 0: 有房认筹 1、无房认筹
				if(IsPaydepositEnum.YES.getNo().equals(payDepositDto.getIsPaydeposit())){
					//无房认筹, 获取字典表dictionary_value = 'NT07' 的消息模板
					//消息模板: 无房认筹：认筹审批申请、房号：${roomName}；客户：${customer}；经纪人：${agent}
					String msgTemp = "认筹审批申请。房号：${roomName}；客户：${customer}；归属人：${agent}";
					String sendMsg = "";
					DictionaryDto dicDto = new DictionaryDto();
					dicDto.setDictionaryValue("NT07");
					Dictionary dic = dictionaryService.selectByDto(dicDto);
					if(dic != null){
						msgTemp = dic.getDictionaryName();
					}
					sendMsg = msgTemp.replace("${roomName}", "无")
							.replace("${customer}", cusName)
							.replace("${agent}", userAgent_gsr.getUserName());
//							.replace("${agent}", userAgent.getUserName());
					//创建提醒消息及消息发送人信息
					Map<String, String> noticeParamMap = new HashMap<String, String>();
					noticeParamMap.put("noticeDicId",  dic.getId()+"");
					noticeParamMap.put("noticeTempType", "NT07");
					noticeParamMap.put("sendMsg", sendMsg);
					noticeParamMap.put("title", "无房认筹");
					noticeParamMap.put("merchantId", String.valueOf(payDepositDto.getMerchantId()));
					noticeParamMap.put("projectCode", payDepositDto.getProjectCode());
					noticeParamMap.put("userCode", payDepositDto.getUserCode());
					noticeParamMap.put("accessCode", payDepositDto.getAccessCode());
					noticeParamMap.put("createUserId", String.valueOf(payDepositDto.getCreateUserId()));
					/*
					 * (ym) 提醒内容增加超链接 start
					 * */
					Map<String,String> replaceValuesMap=new HashMap<String,String>();
					replaceValuesMap.put(MsgUtil.ROOM_ID, "");
					replaceValuesMap.put(MsgUtil.ROOM_NAME, "");
					replaceValuesMap.put(MsgUtil.CUSTOMER_ID, String.valueOf(customer.getId()));
					replaceValuesMap.put(MsgUtil.CUSTOMER_NAME, cusName);
					replaceValuesMap.put(MsgUtil.PRICE_SCHEME_ID, "");
					replaceValuesMap.put(MsgUtil.PRICE_SCHEME_NAME, "");
			    	noticeParamMap.put("replaceValues", MsgUtil.getReplaceValues(replaceValuesMap));
			    	/*
					 * (ym) 提醒内容增加超链接 end
					 * */
					resDto = cusAppNoticeManage.createNotice(noticeParamMap, userList, action);
				}else{
					//有房认筹, 获取字典表dictionary_value = 'NT07' 的消息模板
					//消息模板: 有房认筹：认筹审批申请、房号：${roomName}；客户：${customer}；经纪人：${agent}
					String msgTemp = "认筹审批申请。房号：${roomName}；客户：${customer}；归属人：${agent}";
					String sendMsg = "";
					DictionaryDto dicDto = new DictionaryDto();
					dicDto.setDictionaryValue("NT07");
					Dictionary dic = dictionaryService.selectByDto(dicDto);
					if(dic != null){
						msgTemp = dic.getDictionaryName();
					}
					//项目房间
					String roomContent = "";
					ProjectRoom room = projectRoomService.selectById(payDepositDto.getRoomId());
					if(room != null){
						roomContent = room.getCombinedName();
					}
					sendMsg = msgTemp.replace("${roomName}", roomContent)
							.replace("${customer}", cusName)
							.replace("${agent}", userAgent_gsr.getUserName());
//							.replace("${agent}", userAgent.getUserName());
					//创建提醒消息及消息发送人信息
					Map<String, String> noticeParamMap = new HashMap<String, String>();
					noticeParamMap.put("noticeDicId",  dic.getId()+"");
					noticeParamMap.put("noticeTempType", "NT07");
					noticeParamMap.put("sendMsg", sendMsg);
					noticeParamMap.put("title", "有房认筹");
					noticeParamMap.put("merchantId", String.valueOf(payDepositDto.getMerchantId()));
					noticeParamMap.put("projectCode", payDepositDto.getProjectCode());
					noticeParamMap.put("userCode", payDepositDto.getUserCode());
					noticeParamMap.put("accessCode", payDepositDto.getAccessCode());
					noticeParamMap.put("createUserId", String.valueOf(payDepositDto.getCreateUserId()));
					/*
					 * (ym) 提醒内容增加超链接 start
					 * */
					Map<String,String> replaceValuesMap=new HashMap<String,String>();
					replaceValuesMap.put(MsgUtil.ROOM_ID, String.valueOf(room.getId()));
					replaceValuesMap.put(MsgUtil.ROOM_NAME, roomContent);
					replaceValuesMap.put(MsgUtil.CUSTOMER_ID, String.valueOf(customer.getId()));
					replaceValuesMap.put(MsgUtil.CUSTOMER_NAME, cusName);
					replaceValuesMap.put(MsgUtil.PRICE_SCHEME_ID, "");
					replaceValuesMap.put(MsgUtil.PRICE_SCHEME_NAME, "");
			    	noticeParamMap.put("replaceValues", MsgUtil.getReplaceValues(replaceValuesMap));
			    	/*
					 * (ym) 提醒内容增加超链接 end
					 * */
					resDto = cusAppNoticeManage.createNotice(noticeParamMap, userList, action);
				}
				//推送消息
				if("1".equals(resDto.getResult())){
					//推送消息待处理......
					//pushMsg(project.getProjectCode(), proName, "NT07","认筹审批申请");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			resDto.setErrorCode("00000");
			resDto.setErrorMsg("新增认筹消息失败!");
			resDto.setResult(ResultEnum.FAILURE.getNo());
			return resDto;
		}
		return resDto;
	}
	
	public void pushMsg(String projectCode,String projectName,String noticeTempType,String actionTitle) throws Exception{
		//1、查询认筹审核申请相关推送消息
		// NT07: 认筹审核申请
		List<MessageReceiverDto> msgRecList = new ArrayList<MessageReceiverDto>();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Calendar calendar = Calendar.getInstance();
 		int year = calendar.get(Calendar.YEAR);
 		int month = calendar.get(Calendar.MONTH) + 1;
 		int day = calendar.get(Calendar.DAY_OF_MONTH);
// 		String issueTimeBefore = year + "-" + month + "-" + day + " 00:00:00"; 
 		String issueTimeAfter = year + "-" + month + "-" + day + " 23:59:59"; 
 		MessageReceiverDto withHouseMrDto = new MessageReceiverDto();
 		withHouseMrDto.setNoticeTempType(noticeTempType);
 		withHouseMrDto.setIsSend(IsSendEnum.UNSEND.getNo());
 		//loseCusMrDto.setIssueTimeBefore(sdf.parse(issueTimeBefore));
 		//推送所有小于 issueTimeAfter 时间的所有消息
 		withHouseMrDto.setIssueTimeAfter(sdf.parse(issueTimeAfter));
   	 	List<MessageReceiverDto> withHouseMrList = messageReceiverService.selectPushMsgListByDto(withHouseMrDto);
   	 	if(withHouseMrList != null){
   	 		for(MessageReceiverDto withHouseMr: withHouseMrList){
   	 			msgRecList.add(withHouseMr);
   	 		}
   	 	}
   	 	
   	 	if(msgRecList != null && msgRecList.size() > 0){
   	 		String noticeIds = "";
   	 		String msgRecIds = "";
   	 		Set<String> noticeIdSet = new HashSet<String>();
   	 		for(MessageReceiverDto msgRecDto: msgRecList){
   	 			//开始推送消息
	   	 		Map<String, String> pushMap = new HashMap<String, String>();
		   	 	pushMap.put("action", "认筹提交审核提醒");
		   	 	pushMap.put("remindCategoryId", String.valueOf(msgRecDto.getDictionaryId()));
		   	 	pushMap.put("pushType", msgRecDto.getNoticeTempType());
		   	    pushMap.put("projectCode",projectCode);
		   	    pushMap.put("projectName", projectName);
				String context = msgRecDto.getContent();
				appPushService.pushMessage(String.valueOf(msgRecDto.getReceiverId()), context,
					msgRecDto.getTitle(), pushMap);
				
				//消息ID,Set
				noticeIdSet.add(String.valueOf(msgRecDto.getNoticeId()));
				//消息接收人ID'S
				if(StringUtils.isNotEmpty(msgRecIds)){
					msgRecIds += ",";
				}
				msgRecIds += String.valueOf(msgRecDto.getId());
   	 		}
   	 		//需更新消息ID'S
   	 		if(!noticeIdSet.isEmpty()){
				for(String noticeId: noticeIdSet){
					if(StringUtils.isNotEmpty(noticeIds)){
						noticeIds += ",";
					}
					noticeIds += noticeId;
	   	 		}
   	 		}
   	 		//更新消息
   	 		NoticeDto noticeDto = new NoticeDto();
   	 		noticeDto.setIsSend(IsSendEnum.SEND.getNo());
   	 		noticeService.updates(noticeDto, noticeIds);
   	 		//更新接收人
   	 		MessageReceiverDto updateMRDto = new MessageReceiverDto();
   	 		updateMRDto.setIsSend(IsSendEnum.SEND.getNo());
   	 		messageReceiverService.updates(updateMRDto, msgRecIds);
   	 	}
	}
	
}
